import React, { Component, useEffect, useState } from "react";

import './style.scss';

export interface SwitchProps {
  type?: 'input' | 'button' | null;
  loading?: boolean;
  checked?: boolean;
  leftText?: string;
  rightText?: string;
  onChange?: Function;
};

export class SwitchA extends Component<SwitchProps> {
  private UID = 'UID-' + new Date().getTime();
  public state = {
    checked: false,
    changeAni: ''
  };

  constructor(props: SwitchProps) {
    super(props);
    this.state.checked = !!this.props.checked;
  };
  
  public toggle(e: any): void {
    e.stopPropagation();
    const { onChange = () => {} } = this.props;
    onChange(!this.state.checked);
    this.setState({checked: !this.state.checked});
  };

  componentWillReceiveProps({ checked }: SwitchProps) {
    if(checked !== this.state.checked){
      this.setState({
        changeAni: checked ? '' : '',
        checked
      });
    }
  }

  render() {
    const { checked = false, changeAni } = this.state;
    const { type = 'input' } = this.props;

    return (
      <>
        { type === 'input' ? <input id={ this.UID } className={`mkreact-switch mkreact-switch-${type}`} type="checkbox" checked={checked} onChange={ this.toggle.bind(this) } ></input> : null }
      </>
    )
  }
};

export const Switch = (props: SwitchProps) => {
  const [ check, checkSet ] = useState<boolean>(false);
  const [ changeAni, changeAniSet ] = useState<string>('');
  const UID = 'UID-' + new Date().getTime();
  const { type = 'input', 
          checked = false, 
          loading = false, 
          onChange = () => {},
          leftText = 'ON',
          rightText = 'OFF',
        } = props;

  const toggle = (e: any) => {
    e.stopPropagation();
    onChange(!check);
    checkSet(!check);
  };

  useEffect(() => {
    //当外部传入的checked与内部的check不同时，使用外部的checked值
    if(check !== checked){
      checkSet(checked);
      changeAniSet(checked ? 'mkreact-switch-on_ani' : 'mkreact-switch-off_ani')
    }
  }, [ checked ])

  return (
    <>
      { type === 'input' ? <input id={UID} className={`mkreact-switch mkreact-switch-${type}`} type="checkbox" checked={check} onChange={toggle}></input> : null }
      { type === 'button' ? (
        <span id={ UID }
          className={`mkreact-switch mkreact-switch-${type} mkreact-switch-${check ? 'on' : 'off'}`}
          onClick={ (e: any) => { if(loading){return};  toggle(e)} }>
            { check ? leftText : rightText }
            <span className={`mkreact-switch-ball mkreact-switch-ball-${check ? 'on' : 'off'} ${changeAni}`}>
              { !loading ? <span></span> : null }
            </span>
        </span>
      ) : null }
    </>
  )
};